package com.proxy.server.backend.bio;

import com.proxy.common.exception.ProxyIoException;
import com.proxy.common.model.DataNode;
import com.proxy.common.pool.Pool;
import com.proxy.common.pool.PooledObjectFactory;
import com.proxy.common.pool.common.PoolConfig;
import com.proxy.common.pool.impl.BasePool;
import com.proxy.server.backend.BackendClient;
import com.proxy.server.backend.BackendConnection;

/**
 * Created by liufish on 16/7/25.
 */
public class BioBackendClient implements BackendClient {

    private DataNode node;

    private PooledObjectFactory factory;

    private Pool<BackendConnection> pool;

    public BioBackendClient(DataNode node) {
        this.node = node;
        this._initPool();
    }


    /**
     * 初始化连接池
     */
    private void _initPool() {

        PoolConfig config = new PoolConfig();
        //初始化连接个数
        config.setInitial(node.getInitIdle());
        //最大活动数
        config.setMaxActive(node.getMaxActive());

        //保证获取的连接是可用的
        config.setTestOnBorrow(true);

        //定时对线程池中空闲的链接进行validateObject校验
        config.setTestWhileIdle(true);

        // 失效检查线程运行时间间隔，如果小于等于0，不会启动检查线程
        config.setTimeBetweenEvictionRunsMillis(node.getTimeBetweenEvictionRunsMillis());
        factory = new BioBackendConnectionFactory(this);
        pool = new BasePool<BackendConnection>(config,factory);
    }

    public BackendConnection borrowConnection() {
        try {
            return pool.borrowObject();
        } catch (Exception e) {
            throw new ProxyIoException(e);
        }
    }


    public void returnConnection(BackendConnection connection) {
        pool.returnObject(connection);
    }


    public void shutdown() {
        this.pool.shutdown();
    }


    public DataNode getNode() {
        return this.node;
    }

}
